package com.enhinck.dbutilweb.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 统一响应包装
 *
 * @author huenbin
 * @date 2020-06-02 11:18
 */
@Data
@NoArgsConstructor
@ApiModel("统一响应包装")
public class WebResponse<T> implements Serializable {
    @ApiModelProperty("统一响应内容")
    private T data;
    @ApiModelProperty("错误消息")
    private String msg;
    @ApiModelProperty("响应编码 0为成功")
    private String code;

    protected static final String SUCCESS_CODE = "0";

    /**
     * 数据不存在
     */
    protected static final String NOT_FOUND = "404";

    public WebResponse(T data) {
        this.code = SUCCESS_CODE;
        this.data = data;
    }

    public WebResponse(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 成功的返回
     *
     * @param data 数据
     * @return 正常返回体
     */
    public static <T> WebResponse success(T data) {
        return new WebResponse(data);
    }

    /**
     * 成功的返回
     *
     * @param data 数据
     * @return 正常返回体
     */
    public static <T> WebResponse ok(T data) {
        return new WebResponse(data);
    }
    /**
     * 错误返回
     *
     * @param errorCode    错误码
     * @param errorMessage 错误信息
     * @return 错误返回体
     */
    public static WebResponse error(String errorCode, String errorMessage) {
        return new WebResponse(errorCode, errorMessage);
    }

    @JsonIgnore
    public static WebResponse notFound() {
        return new WebResponse(NOT_FOUND, "数据不存在");
    }

    @JsonIgnore
    public boolean isSuccessful() {
        return SUCCESS_CODE.equals(code);
    }
}
